package cn.lyvust.exam;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class LuckStu extends JFrame {
    public int index = 0;
    public int lines = 0;
    public ArrayList nameList = new ArrayList();

    public static void main(String[] args) {
        LuckStu luckStu = new LuckStu();
    }
    public LuckStu() {
        this.getNames();
        this.setTitle("抽奖程序");
        this.setSize(300, 200);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.init();
        //设置布局
        this.setLayout(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void init() {
        JButton jbStart = new JButton("开始");
        JButton jbEnd = new JButton("结束");
        jbStart.setBounds(32, 107, 93, 37);
        jbEnd.setBounds(165, 107, 93, 37);
        this.add(jbStart);
        this.add(jbEnd);

        JLabel jlStart = new JLabel("开始");
        jlStart.setFont(new Font(Font.DIALOG, Font.BOLD, 30));
        jlStart.setBounds(70, 45, 120, 30);
        this.add(jlStart);

        //定时器
        Timer timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int random = 0;
                Random rand = new Random();
                random = rand.nextInt(lines);

                String name = (String) nameList.get(random);
                jlStart.setText(name);
            }
        });

        //开始按钮的监听响应函数
        jbStart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timer.start();
            }
        });
        //结束按钮的监听响应函数
        jbEnd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timer.stop();
            }
        });
    }

    //读取names.txt里面的所有学生姓名
    public void getNames() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("E:\\zhengguangguo\\java-code2021\\names.txt"));
            String name = br.readLine();
            while (name != null) {
                nameList.add(name);
                name = br.readLine();
                lines ++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
